package com.ikun.service.impl;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.dao.BuildingsDao;
import com.ikun.entity.BuildingManagers;
import com.ikun.entity.Buildings;
import com.ikun.service.BuildingsService;
import com.ikun.util.Result;

/**
 * @ClassName: BuildingsServiceImpl
 * @Author: 吴思伟
 * @CreateTime: 2025-03-28 16:21
 * @Description: TODO
 */

@Service
public class BuildingsServiceImpl extends ServiceImpl<BuildingsDao, Buildings> implements BuildingsService {

    @Autowired
    private BuildingsDao buildingsDao;

    @Override
    public List<Buildings> buildsDetails() {
        return buildingsDao.buildsDetails();
    }

    @Override
    public Result addBuilding(String buildingNumber, String totalFloors, String totalAreas, String location) {
        try {
            int i = buildingsDao.addBuilding(buildingNumber, totalFloors, totalAreas, location);
            if (i == 0) {
                return Result.error("添加失败");
            }
            return Result.success("添加成功");
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                return Result.error("该楼栋编号已存在");
            }
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    // ... 其他代码保持不变 ...

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateManageBuilds(Integer managerId, String[] buildingIds) {
        try {
            // 先删除该管理员原有的楼栋关联
            buildingsDao.deleteByManagerId(managerId);

            // 检查重复buildingId
            Set<Integer> uniqueBuildingIds = new HashSet<>();
            for (String buildingId : buildingIds) {
                int id = Integer.valueOf(buildingId);
                if (!uniqueBuildingIds.add(id)) {
                    return Result.error("楼栋ID重复: " + buildingId);
                }
            }

            // 批量插入新的楼栋关联
            List<BuildingManagers> list = new ArrayList<>();
            for (String buildingId : buildingIds) {
                BuildingManagers bm = new BuildingManagers();
                bm.setManagerId(managerId);
                bm.setBuildingId(Integer.valueOf(buildingId));
                bm.setRelationTime(new Date());
                list.add(bm);
            }

            if (!list.isEmpty()) {
                buildingsDao.batchInsert(list);
            }
            return Result.success("操作成功");
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                return Result.error("该楼已经被其他管家管理,请换一栋!");
            }
            return Result.error("操作失败: " + e.getMessage());
        }
    }

}
